import RSA = require('node-rsa');

const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAMYSCg3ocg3n+N/Fz8i0x6gdSZ7wSO8d1mr5ECEn1v/AVyuIOTeh
lTo4Ql715FfK/rAgHXKKu4JFgcoaUl93zxECAwEAAQJAbppcKvAF4GYMv0hCgx0P
8HyKQ8qBr6TFuu5hZ2JL2HuekFitBtmhTRFWfqRxMhEYMRiYq7G8RvPca+EpauVw
wQIhAPe1TaXE4w6ipU9EaKSv+14NMe2VUDl6cYfjBw0z4841AiEAzLNfgGV2asmy
p8dJgd6VDAp7u0O09DBmWaf3cqOnSO0CIBQ7idkVaNpkLI557vYsraJz/3UBcikP
uEA6KfRJHb1VAiEAnt4LnYuhZumZJUuuygMkbA7qzoCSvP2fQa/xhOBsYVUCIQCK
d14U16qwkKkJNkqHHKmCSeCd6M0X3kNTXL8nIp8EqA==
-----END RSA PRIVATE KEY-----`;

/**
 * 生成RSA密钥对
 * @param keySize 密钥长度
 * @returns 公钥和私钥
 */
export const generateRSAkey = (keySize: number = 512) => {
  const nodeKey = new RSA({ b: keySize });
  const pubkey = nodeKey.exportKey('public');
  const prikey = nodeKey.exportKey('private');
  return { pubkey, prikey };
};

/**
 * RSA加密
 * @param text  加密文本
 * @param pubkey 公钥
 * @returns 加密后的文本
 */
export const encryptRSA = (text: string, pubkey: string = privateKey) => {
  const nodeKey = new RSA(pubkey);
  nodeKey.setOptions({ encryptionScheme: 'pkcs1' });
  return nodeKey.encrypt(text, 'base64');
};

/**
 * RSA解密
 * @param text 解密文本
 * @param prikey 私钥
 * @returns 解密后的文本
 */
export const decryptRSA = (text: string, prikey: string = privateKey) => {
  const nodeKey = new RSA(prikey);
  nodeKey.setOptions({ encryptionScheme: 'pkcs1' });
  return nodeKey.decrypt(text, 'utf8');
};
